import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Select, TreeSelect, DatePicker, Checkbox, message, Dropdown, Menu, Icon } from 'antd'
import _ from 'lodash'
import moment from 'moment'

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, confirmDelete, getYear, getPayCycleDom } from 'lib/fun'

const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const { RangePicker } = DatePicker;
const Option = Select.Option;

class Filter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      selectedCode: ''
    }
  }

  componentDidMount(){
    this.loadArea();
  }

  loadArea = (treeNode)=>{
    console.log('load area');
    var self = this;
    var selected = findRowData(self.state.treeData, treeNode?treeNode.props.eventKey:0, 'areaId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        resolve();
      }else{
        Ajax({
          url: '/area/list',
          data: {
            areaParentId: treeNode?treeNode.props.eventKey:0,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list, 'areaId');
            }else{
              treeData = data.list;
            }
            self.setState({
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  handleSearch = (e) => {
    var self = this;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      values.state = values.state?[values.state]:[];
      self.props.handleFilter(values);
    });
  }

  selectChange = (value)=>{
    this.setState({
      selectedCode: value
    });
    this.props.form.setFieldsValue({
      subsidyCount: ""
    });
  }

  handleReset = () => {
    this.props.form.resetFields();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const formItemLayout2 = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };
    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""}>{loop(item.children)}</SelectTreeNode>;
      }
      console.log('isLeaf',item.children&&item.children.length == 0 );
      return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);
    const years = getYear();

    const { payCycleCode } = this.props.config;
    const state = this.props.state||800;
    const projectRegisterBatchEn = _.filter(this.props.common.projectRegisterBatchEn||[], (obj)=>{
      return obj.code >= state
    });

    return (<Form
          horizontal
          className="ant-advanced-search-form"
          onSubmit={this.handleSearch}
        >
          <Row gutter={20}>
            <Col span={6}>
              <FormItem {...formItemLayout} label="补贴登记区划">
                {getFieldDecorator("areaId")(
                  <TreeSelect
                    allowClear
                    size="default"
                    loadData={ this.loadArea }
                    dropdownMatchSelectWidth={false}
                  >
                    { treeNodes }
                  </TreeSelect>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="补贴项目">
                {getFieldDecorator("projectId")(
                  <Select
                    allowClear
                    size="default"
                    dropdownMatchSelectWidth={false}
                  >
                  {
                    this.props.projectList.map((obj)=>{
                      return (<Option key={obj.projectId}>{ obj.projectName }</Option>)
                    })
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="发放年度">
                {getFieldDecorator("year")(
                  <Select
                    allowClear
                    size="default"
                  >
                  {
                    years.map((obj)=>{
                      return (<Option key={obj}>{ obj }</Option>)
                    })
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="发放周期">
                {getFieldDecorator("payCycleCode")(
                  <Select
                    allowClear
                    size="default"
                    onChange={this.selectChange}
                  >
                  {
                    (payCycleCode||[]).map(function(obj){
                      return (<Option key={obj.dictionaryId} value={ obj.dictionaryCode }>{ obj.dictionaryName }</Option>)
                    })
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={6}>
              <FormItem {...formItemLayout} label="发放次数">
                {getFieldDecorator("subsidyCount")(
                  <Select
                    allowClear
                    size="default"
                  >
                  {
                    this.state.selectedCode?getPayCycleDom(this.state.selectedCode):null
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label="状态">
                {getFieldDecorator("state")(
                  <Select
                    allowClear
                    size="default"
                    dropdownMatchSelectWidth={false}
                  >
                  {
                    (projectRegisterBatchEn||[]).map(function(obj){
                      return (<Option key={obj.code} value={ obj.code+"" }>{ obj.mean }</Option>)
                    })
                  }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={12}>
              <div className="btn-box">
                <Button type="primary" htmlType="submit">查询</Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                  重置
                </Button>
              </div>
            </Col>
          </Row>
        </Form>);
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

module.exports = connect(mapStateToProps)(Form.create()(Filter))